package com.it.sun.easychat.framework.security.handler;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.it.sun.easychat.common.context.Current;
import com.it.sun.easychat.common.context.RequestContext;
import com.it.sun.easychat.model.util.ResultHelper;
import com.it.sun.esaychat.user.entity.UserEntity;
import com.it.sun.esaychat.user.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author sunmannian
 * @ClassName com.it.sun.easychat.framework.security.handler.LoginSuccessHandler
 * @Date 2020/5/24 20:15
 * @Version V1.0
 * Description  <登陆成功的处理>
 * Copyright (C) 北京中电兴发科技有限公司  since 2020/5/24
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication)
            throws IOException, ServletException {
        chain.doFilter(request, response);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 登陆成功后返回用户信息，权限信息
        HttpSession session = request.getSession();
        Current current = (Current) session.getAttribute(Current.CURRENT_NAME);
        User user = (User) authentication.getPrincipal();
        // 保存用户认证信息
        current.setUser(user);
        user.setPassword(null);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().write(JSON.toJSONString(ResultHelper.getSuccess(user)));
    }
}
